package com.quectel.mobile.controller.forum;

import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.forum.ForumMuteBusiness;
import com.quectel.business.common.forum.vo.ForumMuteVo;
import com.quectel.business.contentaudit.ValidatorChain;
import com.quectel.business.contentaudit.ValidatorContext;
import com.quectel.constant.core.forum.ForumConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.forum.dto.mongo.ForumCommentDto;
import com.quectel.core.module.forum.dto.mongo.ForumPostDto;
import com.quectel.core.module.forum.service.mongo.ForumCommentService;
import com.quectel.core.module.forum.service.mongo.ForumPostService;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.mobileuser.dto.MobileUserDto;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.mobile.vo.forum.ForumCommentCommentReq;
import com.quectel.mobile.vo.forum.ForumCommentLikeReq;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/5/15 9:24
 * @description new java file header...
 */
@RestController
@RequestMapping("forumComment")
@Tag(name = "ForumCommentController", description = "发帖评论相关api")
public class ForumCommentController extends BaseController {
    @DubboReference
    private ForumCommentService forumCommentService;
    @DubboReference
    private ForumPostService forumPostService;

    @Autowired
    private ValidatorChain validatorChain;
    @Autowired
    private ForumMuteBusiness forumMuteBusiness;


    /**
     * 删除
     */
    @PostMapping("delete")
    @Operation(summary = "根据Id删除评论")
    public Response<Object> delete(@RequestBody Long id) {
        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();
        if (currentHousehold == null) {
            return Response.error("请先认证住户");
        }

        ForumCommentDto forumCommentDto = forumCommentService.selectById(id);
        if (forumCommentDto == null || SystemConstants.YES.equals(forumCommentDto.getDeletedFlag())) {
            return Response.error("评论已经被删除");
        }
        ForumPostDto forumPostDto = forumPostService.selectById(forumCommentDto.getForumPostId());
        if (forumPostDto == null || SystemConstants.YES.equals(forumPostDto.getDeletedFlag())) {
            return Response.error("帖子已经被删除");
        }

        MobileUserDto mobileUser = SessionHolder.getLoginMobileUserSession().getMobileUser();
        //不是自己的评论并且不是自己的帖子 都不可以删除
        if(!mobileUser.getId().equals(forumCommentDto.getPersonId()) && !mobileUser.getId().equals(forumPostDto.getAuthorId())){
            return Response.error("您没有操作权限");
        }


        //标记删除
        forumCommentService.batchLogicDeleteById(forumPostDto.getId(),id);

        return Response.ok();
    }

    /**
     * 点赞 不需要认证
     *
     * @param forumCommentLikeReq
     * @return
     */
    @PostMapping(value = "like")
    @Operation(summary = "点赞,取消点赞操作")
    public Response<Object> like(
            @RequestBody ForumCommentLikeReq forumCommentLikeReq
    ) {
        if (!forumCommentLikeReq.getStatus().equals(SystemConstants.YES) && !forumCommentLikeReq.getStatus().equals(SystemConstants.NO)) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        //查询帖子
        ForumCommentDto dto = forumCommentService.selectById(forumCommentLikeReq.getCommentId());

        if (dto == null || SystemConstants.YES.equals(dto.getDeletedFlag())) {
            return Response.error("您要点赞的评论已被删除");
        }

        //执行
        forumCommentService.like(dto.getId(), SessionHolder.getLoginMobileUserSession().getMobileUser().getId(), forumCommentLikeReq.getStatus());
        return Response.<Object>ok().wrap(null);
    }


    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @Operation(summary = "通过Id查询评论详情")
    public Response<ForumCommentDto> info(@PathVariable("id") Long id) {

        //查询帖子
        ForumCommentDto dto = forumCommentService.selectById(id);

        if (dto == null || SystemConstants.YES.equals(dto.getDeletedFlag())) {
            return Response.error("帖子不存在或已被删除");
        }

        if (SessionHolder.getLoginMobileUserSession()!=null && SessionHolder.getLoginMobileUserSession().getMobileUser() != null) {
            //是否是作者
            Long currentUser = SessionHolder.getLoginMobileUserSession().getMobileUser().getId();
            dto.setAuthorFlag(forumCommentService.isAuthor(dto.getPersonId(),currentUser));
            //是否点过赞
            dto.setLikeFlag(forumCommentService.ifLike(dto.getId(),currentUser));
        }

        return Response.<ForumCommentDto>ok().wrap(dto);
    }


    /**
     * 评论需要认证
     *
     * @param forumCommentCommentReq
     * @return
     */
    @PostMapping(value = "comment")
    @Operation(summary = "发布评论的评论")
    public Response<Object> comment(
            @RequestBody ForumCommentCommentReq forumCommentCommentReq
    ) {
        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();
        if (currentHousehold == null) {
            return Response.error("请先进行身份认证");
        }
        //黑名单查询
        ForumMuteVo muteStatus = forumMuteBusiness.getMuteStatus(SessionHolder.getLoginMobileUserSession().getTenantId(), SessionHolder.getLoginMobileUserSession().getMobileUser().getId());
        if(muteStatus!=null && SystemConstants.NO.equals(muteStatus.getStatus())){
            return Response.error(muteStatus.getRecordText());
        }

        //查询帖子
        ForumCommentDto forumCommentDto = forumCommentService.selectById(forumCommentCommentReq.getCommentId());

        if (forumCommentDto == null || SystemConstants.YES.equals(forumCommentDto.getDeletedFlag())) {
            return Response.error("您要评论的帖子已被删除");
        }

        //校验发帖内容
        ValidatorContext validatorContext = new ValidatorContext();
        validatorContext.setTenantId(SessionHolder.getLoginMobileUserSession().getTenantId());
        validatorContext.setVillageId(SessionHolder.getLoginMobileUserSession().getCurrentVillageId());
        validatorContext.setText(forumCommentCommentReq.getComment());

        Response validateResult = validatorChain.validate(validatorContext);
        if (!validateResult.isSuccess()) {
            return Response.<Object>ok().wrap(validateResult);
        }

        //执行
        forumCommentService.comment(forumCommentDto.getId(), SessionHolder.getLoginMobileUserSession().getMobileUser().getId(), currentHousehold.getId(), forumCommentCommentReq.getComment());
        return Response.<Object>ok().wrap(null);
    }


    @GetMapping("list")
    @Operation(summary = "列表")
    public Response<Page<ForumCommentDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "帖子Id") @RequestParam Long postId
    ) {
        //查看帖子是否存在
        ForumPostDto dto = forumPostService.selectById(postId);
        if(dto==null || SystemConstants.YES.equals(dto.getDeletedFlag())){
            return Response.error("帖子不存在或被删除");
        }
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        request.put(LambdaUtil.getFieldName(ForumCommentDto::getForumPostId), postId);
        //只查询一级评论
        request.put(LambdaUtil.getFieldName(ForumCommentDto::getParentId), -1L);
        //未删除评论
        request.put(LambdaUtil.getFieldName(ForumCommentDto::getDeletedFlag),SystemConstants.NO);

        if (SessionHolder.getLoginMobileUserSession()!=null && SessionHolder.getLoginMobileUserSession().getMobileUser() != null) {
            //当前用户 用来标记帖子是否是自己的
            request.put(ForumConstants.CURRENT_USER, SessionHolder.getLoginMobileUserSession().getMobileUser().getId());
        }

        List<ForumCommentDto>  forumCommentDtoList = forumCommentService.queryList(request.getParams());
        //不查询total提高性能,totalCount前端也用不上
        Page<ForumCommentDto> page = new Page<>(request.getPageNo(), request.getPageSize(), dto.getCommentCount(), forumCommentDtoList);
        return Response.<Page<ForumCommentDto>>ok().wrap(page);
    }

    @GetMapping("commentList")
    @Operation(summary = "评论列表")
    public Response<Page<ForumCommentDto>> commentList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "帖子Id") @RequestParam Long postId,
            @Parameter(description = "评论Id") @RequestParam Long commentId


    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        ForumCommentDto forumCommentDto = forumCommentService.selectById(commentId);
        if (forumCommentDto == null || SystemConstants.YES.equals(forumCommentDto.getDeletedFlag())) {
            return Response.error("评论不存在或被删除");
        }

        request.put(LambdaUtil.getFieldName(ForumCommentDto::getForumPostId), postId);
        request.put(LambdaUtil.getFieldName(ForumCommentDto::getId), commentId);
        //未删除评论
        request.put(LambdaUtil.getFieldName(ForumCommentDto::getDeletedFlag),SystemConstants.NO);

        if (SessionHolder.getLoginMobileUserSession()!=null && SessionHolder.getLoginMobileUserSession().getMobileUser() != null) {
            //当前用户 用来标记评论是否是自己的
            request.put(ForumConstants.CURRENT_USER, SessionHolder.getLoginMobileUserSession().getMobileUser().getId());
        }

        List<ForumCommentDto>  forumCommentDtoList = forumCommentService.commentList(request.getParams());

        forumCommentDtoList.forEach(comment -> {
            //如果不是父级评论 则需要查询对应评论的详情
            if(!commentId.equals(comment.getId())){
                ForumCommentDto parentComment = forumCommentService.selectCacheById(comment.getParentId());
                comment.setForumComment(parentComment);
            }
        });

        //不查询total提高性能,totalCount前端也用不上
        Page<ForumCommentDto> page = new Page<>(request.getPageNo(), request.getPageSize(), forumCommentDto.getCommentCount(), forumCommentDtoList);
        return Response.<Page<ForumCommentDto>>ok().wrap(page);
    }

}
